import socket
import paramiko
import threading
import sys

host_key = paramiko.RSAKey(filename="/root/.ssh/id_rsa")
paramiko.util.log_to_file("server.log")

class Server(paramiko.ServerInterface):
    def __init__(self):
        self.event = threading.Event()

    def check_channel_request(self, kind, chanid):
        print "in check channel request"
        if kind == "session":
            return paramiko.OPEN_SUCCEEDED
        return paramiko.OPENFAILED_ADMINISATRATIVELY_PROHIBIED

    def check_auth_password(self, username, password):
        print "in check auth passwd"
        if(username == "root") and (password == "toor"):
            return paramiko.AUTH_SUCCESSFUL
        return paramiko.AUTH_FAILED
    def check_channel_pty_request(self, channel, term, width, height, pixelwidth,
                                  pixelheight, modes):
        return True

server = sys.argv[1]
ssh_port = int(sys.argv[2])

try:
    sock  = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind((server, ssh_port))
    sock.listen(100)

    print "[+] Listening for connection ..."
    client, addr = sock.accept()

except Exception, e:
    print "[-] Listen failed: %s" %(str(e))
    sys.exit(1)
print "[+] Got a connection!"

if not client:
    print("accept error")
    sys.exit(1)
try:

    bhSession = paramiko.Transport(client)
    bhSession.add_server_key(host_key)
    print("[+] add server key")
    server = Server()

    try:
        bhSession.start_server(server = server)
    except paramiko.SSHException, x:
        print "[-] SSH negotiation failed."
        sys.exit(1)

    chan = bhSession.accept(20)
    if chan is None:
        print('[-] No channel.')
        sys.exit(1)
    print "[+] Authenticated!"
    print chan.recv(1024)
    chan.send("welcome to bh_ssh")
    while True:
        try:
            command = raw_input("Enter command: ").strip("\n")
            if command != "exit":
                chan.send(command)
                print chan.recv(1024) + "\n"
            else:
                chan.send("exit")
                print "exiting"
                bhSession.close()
                raise Exception("exit")
        except KeyboardInterrupt:
            bhSession.close()
except Exception, e:
    print "[-] Caught exception: %s" %(str(e))
    try:
        bhSession.close()
    except:
        pass
    sys.exit(1)